package com.example.lxj.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.lxj.entity.LoginUser;
import com.example.lxj.entity.SysUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = Optional.ofNullable(username)
                .map(it -> sysUserService.getOne(Wrappers.<SysUser>lambdaQuery()
                        .eq(SysUser::getName, it)
                        .last("limit 1")))
                .orElseThrow(() -> new RuntimeException("获取用户信息失败"));
        // 转为 UserDetails 对象
        return LoginUser.builder()
                .sysUser(user)
                .build();
    }
}
